<?php


namespace app\miniapp\controller;


use app\common\controller\Api;
use app\miniapp\model\OrderModel;
use app\miniapp\model\RepairModel;
use app\miniapp\validate\RepairValidate;
use think\Db;

class Repair extends Base
{
    protected $noNeedLogin = '*';

    //查询设备报修列表
    public function list()
    {
        $data = OrderModel::order('id','DESC')
            ->where('user_id',$this->userId)
            ->field('id,image,goods_name,price,deposit,repa_switch,ddbh')
            ->select();
        $this->success('查询成功',[
            'list' => $data
        ]);
    }

    //提交设备报修
    public function add()
    {
        $data = input('post.');
        $validate = new RepairValidate();
        $res = $validate->scene('add')->check($data);
        if (!$res) {
            $this->error($validate->getError());
        }
        $order = OrderModel::find($data['order_id']);
       // halt($order['repa_switch']);
        if (!$order) {
            $this->error('订单ID不正确');
        }
        if ($order['repa_switch'] != '未报修') {
            $this->error('订单已维修');
        }
        $data['image'] = '/' . ltrim($order['image'],request()->domain());
        $data['goods_name'] = $order['goods_name'];
        $data['price'] = $order['price'];
        $data['price'] = $order['price'];
        $data['deposit'] = $order['deposit'];
        $data['ddbh'] = $order['ddbh'];
        $data['create_time'] = date('Y-m-d H:i:s');
        Db::startTrans();
        $result = false;
        try {
            $add = Db::name('repair')->insert($data);
            $update = Db::name('order')->where('id',$data['order_id'])->update(['repa_switch' => 1]);
            if ($add && $update) {
                $result = true;
            }
        } catch (\Exception $exception) {
            Db::rollback();
            $this->error('失败');
        }
        if ($result) {
            Db::commit();
            $this->success('提交成功');
        } else {
            Db::rollback();
            $this->error('提交失败');
        }
    }

}